import logging
import pandas as pd
from flask import request, jsonify, Blueprint
import numpy as np
from util.webUtils import result
from service.modelServer import modelPredictServer

model_bp = Blueprint('modeController', __name__)
logger = logging.getLogger(__name__)

@model_bp.route('/predicted', methods=['POST'])
def predicted():
    logger.info('Predicted mode')

    # 检查请求是否包含JSON数据
    if not request.is_json:
        logger.info('Request must be JSON')
        return jsonify({'error': 'Request must be JSON'}), 400

    # 从请求中获取数据
    data = request.get_json()
    if 'data' not in data or not isinstance(data['data'], list):
        logger.info('Data must be a list of floats')
        return jsonify({'error': 'Data must be a list of floats'}), 400

    # 将数据转换为numpy数组
    raw_data = np.array(data['data'], dtype=np.float32)
    
    # 均匀降采样到3000个点，保持数据顺序
    target_length = 3000
    raw_length = len(raw_data)
    if raw_length > target_length:
        # 计算采样步长
        step = raw_length / target_length
        # 根据步长均匀选择索引
        indices = np.floor(np.arange(0, raw_length, step)).astype(int)
        # 确保最后一个索引是最后一个数据点
        if indices[-1] != raw_length - 1:
            indices = np.append(indices, raw_length - 1)
        # 如果超过了目标长度，截断到3000个点
        if len(indices) > target_length:
            indices = indices[:target_length]
        segment_data = raw_data[indices]
    else:
        # 如果原始数据长度小于或等于目标长度，直接使用原始数据
        segment_data = raw_data

    # 调用模型预测服务
    predicted = modelPredictServer(segment_data)
    return result(predicted)





